<template>
    <div class="app-container">
        <el-row :gutter="20">
            <!-- 左侧部门tree -->
            <el-col :lg="4" :xs="24" class="mb-[12px]">
                <!-- 这里的v-model指令用于在父组件中将deptId属性与dept-tree组件的值进行双向绑定 -->
                <dept-tree v-model:deptOptions="deptOptions" v-model="queryParams.deptId" @node-click="handleQuery" />
            </el-col>

            <el-col :span="24" :xs="24" :lg="20" class="pr-2.5 pl-2.5 is-guttered">
                <!-- Search start -->
                <div class="search-container">
                    <el-form :inline="true" :model="queryParams">
                        <el-form-item>
                            <span class="bs-form-label"> <span class="icon">姓名:</span> </span>
                            <el-input v-model="queryParams.name" style="width: 140px;" maxlength="20"
                                placeholder="请输入姓名" clearable @keyup.enter.native="handleQuery" />
                        </el-form-item>
                        <el-form-item>
                            <span class="bs-form-label"> <span class="icon">员工编号:</span> </span>
                            <el-input v-model="queryParams.userNumber" style="width: 140px;" maxlength="20"
                                placeholder="请输入员工编号" clearable @keyup.enter.native="handleQuery" />
                        </el-form-item>

                        <el-form-item>
                            <span class="bs-form-label" style="width: 80px"> <span class="icon">创建时间:</span> </span>
                            <el-date-picker v-model="dateTimeRange" type="daterange" range-separator="至"
                                start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD"
                                format="YYYY年MM月DD日" />
                        </el-form-item>
                        <el-form-item>
                            <el-button class="bs-form-btn" type="primary" @click="handleQuery">查询</el-button>
                        </el-form-item>
                    </el-form>
                </div>
                <!-- Search end -->

                <!-- Table start -->
                <el-card shadow="never" class="table-container">
                    <template #header>
                        <div class="flex flex-justify-between">
                            <div>
                                <el-button v-hasPerm="['sys:user:add']" type="success" @click="handleOpenDialog()">
                                    <i-ep-plus />
                                    新增
                                </el-button>
                                <el-button v-hasPerm="['sys:user:delete']" type="danger"
                                    :disabled="removeIds.length === 0" @click="handleDelete()">
                                    <i-ep-delete />
                                    删除
                                </el-button>
                            </div>
                            <div>
                                <el-button class="ml-3" @click="handleOpenImportDialog">
                                    <template #icon><i-ep-upload /></template>
                                    导入
                                </el-button>

                                <el-button class="ml-3" @click="handleExport">
                                    <template #icon><i-ep-download /></template>
                                    导出
                                </el-button>
                            </div>
                        </div>
                    </template>

                    <el-table v-loading="loading" :data="pageData" @selection-change="handleSelectionChange">
                        <el-table-column type="selection" width="50" align="center" />
                        <el-table-column key="id" label="编号" align="center" prop="id" width="100" />
                        <el-table-column key="username" label="用户名" align="center" prop="userName" />
                        <el-table-column label="用户昵称" width="120" align="center" prop="nickName" />
                        <el-table-column label="性别" width="100" align="center" prop="genderLabel" />
                        <el-table-column label="部门" width="120" align="center" prop="deptName" />
                        <el-table-column label="手机号码" align="center" prop="mobile" width="120" />
                        <el-table-column label="状态" align="center" prop="status">
                            <template #default="scope">
                                <el-tag :type="scope.row.status == 1 ? 'success' : 'info'">
                                    {{ scope.row.status == 1 ? "启用" : "禁用" }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="创建时间" align="center" prop="createTime" width="180" />
                        <el-table-column label="操作" fixed="right" width="220">
                            <template #default="scope">
                                <el-button v-hasPerm="['sys:user:password:reset']" type="primary" size="small" link
                                    @click="hancleResetPassword(scope.row)">
                                    <i-ep-refresh-left />
                                    重置密码
                                </el-button>
                                <el-button v-hasPerm="['sys:user:edit']" type="primary" link size="small"
                                    @click="handleOpenDialog(scope.row.id)">
                                    <i-ep-edit />
                                    编辑
                                </el-button>
                                <el-button v-hasPerm="['sys:user:delete']" type="danger" link size="small"
                                    @click="handleDelete(scope.row.id)">
                                    <i-ep-delete />
                                    删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <!-- v-model:page="queryParams.page" 是把分页控件中的page属性与queryParams.page绑定 -->
                    <!-- 这里必须要用v-model:limit这种方式 才能实现双向绑定 -->
                    <Pagination :hidden="false"
                    v-model:total="tableTotal" v-model:page="queryParams.page"
                    v-model:limit="queryParams.limit" @pagination="requestList" />
                </el-card>
                <!-- Table end -->
            </el-col>
        </el-row>

        <!-- 用户表单弹窗 -->
        <el-drawer
        v-model="dialog.visible"
        :title="dialog.title"
        append-to-body
        @close="handleCloseDialog"
        >
        <!-- 用户新增/编辑表单 -->
        <el-form
            ref="userFormRef"
            :model="formData"
            :rules="rules"
            label-width="80px"
        >
            <el-form-item label="用户名" prop="userName">
            <el-input
                v-model="formData.userName"
                :readonly="!!formData.id"
                placeholder="请输入用户名"
            />
            </el-form-item>

            <el-form-item label="用户昵称" prop="nickName">
                <el-input v-model="formData.nickName" placeholder="请输入用户昵称" />
            </el-form-item>

            <el-form-item label="所属部门" prop="deptCode">
            <el-tree-select
                v-model="formData.deptCode"
                placeholder="请选择所属部门"
                :data="deptOptions"
                filterable
                check-strictly
                :render-after-expand="false"
            />
            </el-form-item>

            <el-form-item label="性别" prop="gender">
                <dictionary v-model="formData.genderKey" code="sex" />
            </el-form-item>

            <el-form-item label="角色" prop="roles">
            <el-select v-model="formData.roleCodes" filterable multiple placeholder="请选择">
                <el-option
                v-for="item in roleOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                />
            </el-select>
            </el-form-item>

            <el-form-item label="手机号码" prop="mobile">
            <el-input
                v-model="formData.mobile"
                placeholder="请输入手机号码"
                maxlength="11"
            />
            </el-form-item>

            <el-form-item label="邮箱" prop="email">
            <el-input
                v-model="formData.email"
                placeholder="请输入邮箱"
                maxlength="50"
            />
            </el-form-item>

            <el-form-item label="状态" prop="status">
            <el-radio-group v-model="formData.status">
                <el-radio :value="1">正常</el-radio>
                <el-radio :value="0">禁用</el-radio>
            </el-radio-group>
            </el-form-item>
        </el-form>

        <template #footer>
            <div class="dialog-footer">
            <el-button type="primary" @click="handleSubmit">确 定</el-button>
            <el-button @click="handleCloseDialog">取 消</el-button>
            </div>
        </template>
        </el-drawer>
        <el-overlay style="z-index: 2015; display: none;"></el-overlay>
    </div>
</template>

<script lang="ts" setup>
import TimeUtils from '@/utils/timeUtils'
import { getUserList, deleteUser, resetPwd, UserPageVO, UserForm, editUser, addUser } from '@/api/system/user'
import { getDictRole } from '@/api/base/base' // 角色数据

const tableRef = ref()
const loading = ref(false)
const removeIds = ref<Number[]>([])
const tableTotal = ref(0)
const tableLoading = ref(false)
const pageData = ref<UserPageVO[]>()
const queryParams = reactive({
    page: 1,
    limit: 10,
    startDate: '',
    endDate: '',
    name: '',
    userNumber: '',
    deptId: ''
})

// 日期选择控件
const dateTimeRange = ref("");
watch(dateTimeRange, (newVal) => {
    if (newVal) {
        queryParams.startDate = newVal[0];
        queryParams.endDate = newVal[1];
    } else {
        queryParams.startDate = '';
        queryParams.endDate = '';
    }
});
const selectedRows = ref<UserPageVO[]> // 勾选一行或多行数据

// 部门数据 和 子组件同步
const deptOptions = ref<SelectOptionType[]>([])
 
// 如果你希望数据初始化后立即显示在界面上，
onMounted(() => {
    requestList() // 查询列表数据
})
// 表单数据
const userFormRef = ref(ElForm);

// 角色信息 initRoleOptions() // 角色数据绑定
const roleOptions = ref<SelectOptionType[]>([])
const initRoleOptions = () => {
    getDictRole().then((res) => {
        roleOptions.value = res.data
    })
}
// 角色数据----------------------

// 数据查询
const requestList = () => {
    var params = JSON.parse(JSON.stringify(queryParams))
    tableLoading.value = true
    getUserList(params)
        .then((res) => {
            const { data } = res
            tableLoading.value = false
            pageData.value = data.data
            tableTotal.value = data.total
        })
        .catch((err) => {
            tableLoading.value = false
            console.log(JSON.stringify(err))
        })
}

const handleQuery = () => {
    queryParams.page = 1
    requestList()
}
// 数据查询结束

// 按钮事件
const isEditable = ref<boolean>(false);
/** 行复选框选中记录选中ID集合 */
const handleSelectionChange = (selection: UserPageVO[]) => {
  removeIds.value = selection.map((item: any) => item.id);
}

/**  用户弹窗对象  */
const dialog = reactive({
  visible: false,
  title: "",
});

/** 导入弹窗显示状态 */
const importDialogVisible = ref(false);



/** 用户表单校验规则  */
const rules = reactive({
  username: [{ required: true, message: "用户名不能为空", trigger: "blur" }],
  nickname: [{ required: true, message: "用户昵称不能为空", trigger: "blur" }],
  deptId: [{ required: true, message: "所属部门不能为空", trigger: "blur" }],
  roleIds: [{ required: true, message: "用户角色不能为空", trigger: "blur" }],
  email: [
    {
      pattern: /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/,
      message: "请输入正确的邮箱地址",
      trigger: "blur",
    },
  ],
  mobile: [
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
});

/** 重置密码 */
function hancleResetPassword(row: { [key: string]: any }) {
    ElMessageBox.prompt(
        "请输入用户「" + row.username + "」的新密码",
        "重置密码",
        {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
        }
    ).then(
        ({ value }) => {
            if (!value || value.length < 6) {
                // 检查密码是否为空或少于6位
                ElMessage.warning("密码至少需要6位字符，请重新输入");
                return false;
            }
            //   UserAPI.updatePassword(row.id, value).then(() => {
            //     ElMessage.success("密码重置成功，新密码是：" + value);
            //   });
        },
        () => {
            ElMessage.info("已取消重置密码");
        }
    );
}



//修改 新增用户------------------------------------------------------
// 用户表单数据
const formData = reactive<UserForm>({
  status: 1,
});
/**
 * 打开弹窗
 *
 * @param id 用户ID
 */
 async function handleOpenDialog(id?: number) {
    dialog.visible = true;
    initRoleOptions()

    if (id) {
        dialog.title = "修改用户";
        const editUser = pageData.value?.find(x => x.id === id);
        Object.assign(formData, editUser);
    } else {
        dialog.title = "新增用户";
    }
}

/** 关闭弹窗 */
function handleCloseDialog() {
    dialog.visible = false;
    userFormRef.value.resetFields();
    userFormRef.value.clearValidate();

    formData.id = undefined;
    formData.status = 1;
}

/** 删除用户 */
function handleDelete(id?: number) {
    let userIds: Number[] = []
    if(id){
        userIds = [id]
    }else{
        userIds = removeIds.value //.join(",");
    }
    let param = {
        userIds: userIds
    }
    if (!userIds) { 
        ElMessage.warning("请勾选删除项");
        return;
    }

    ElMessageBox.confirm("确认删除用户?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    }).then(
        function () {
            loading.value = true;
            deleteUser({userIds: userIds}).then(res => {
                ElMessage.success("删除成功");
                handleQuery();

            })
            .finally(() => (loading.value = false));
        },
        function () {
            ElMessage.info("已取消删除");
        }
    );
}

/** 表单提交 */
const handleSubmit = useThrottleFn(() => {
  userFormRef.value.validate((valid: any) => {
    if (valid) {
      const userId = formData.id;
      loading.value = true;
      if (userId) {
        editUser(formData).then((res) => {
            ElMessage.success("修改用户成功");
            handleCloseDialog();
            handleQuery();
        }).finally(() => (loading.value = false));
      } else {
        addUser(formData).then((res) => {
            ElMessage.success("新增用户成功");
            handleCloseDialog();
            handleQuery();
        }).finally(() => (loading.value = false));
      }
    }
  });
}, 3000);
//修改 新增用户结束------------------------------------------------------


/** 打开导入弹窗 */
function handleOpenImportDialog() {
  importDialogVisible.value = true;
}

/** 导入用户成功 */
function handleOpenImportDialogSuccess() {
  handleQuery();
}

/** 导出用户 */
function handleExport() {
//   UserAPI.export(queryParams).then((response: any) => {
//     const fileData = response.data;
//     const fileName = decodeURI(
//       response.headers["content-disposition"].split(";")[1].split("=")[1]
//     );
//     const fileType =
//       "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8";

//     const blob = new Blob([fileData], { type: fileType });
//     const downloadUrl = window.URL.createObjectURL(blob);

//     const downloadLink = document.createElement("a");
//     downloadLink.href = downloadUrl;
//     downloadLink.download = fileName;

//     document.body.appendChild(downloadLink);
//     downloadLink.click();

//     document.body.removeChild(downloadLink);
//     window.URL.revokeObjectURL(downloadUrl);
//   });
}
</script>

<style lang="scss" scoped>
.search-container {
    padding: 18px 0 0 10px;
    margin-bottom: 10px;
    background-color: var(--el-bg-color-overlay);
    border: 1px solid var(--el-border-color-light);
    border-radius: 4px;
    box-shadow: var(--el-box-shadow-light);
}
</style>